package com.paypalpay.controller.outside;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.paypalpay.entity.channelaccess.request.RequestChannelAccess;
import com.paypalpay.entity.channelaccess.request.RequestChannelAccessData;
import com.paypalpay.entity.channelaccess.response.ResponseChannelAccess;
import com.paypalpay.entity.channelaccess.response.ResponseChannelAccessData;
import com.paypalpay.entity.channelaccess.response.ResponseChannelAccessTradeData;
import com.paypalpay.entity.common.DevicePartnerAccess;
import com.paypalpay.external.utils.UtilsInterfacesPackage;
import com.paypalpay.pojo.Constant;
import com.paypalpay.service.DevicePartnerAccessService;
import com.paypalpay.service.SequenceService;
import com.paypalpay.util.wx.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 合作方对接提供的接口
 *
 * @author lm
 */
@RestController
@Api(description = "渠道合作方统一接口入口")
public class PartnerAccessController {

    @Autowired
    DevicePartnerAccessService devicePartnerAccessService;

    @Autowired
    SequenceService sequenceService;

    /***
     * 合作伙伴统一的请求接口入口
     * @param
     * @return
     */
    @CrossOrigin
    @ApiOperation(value = "合作伙伴统一的请求接口入口", response = ResponseChannelAccess.class)
    @RequestMapping(value = "/accessError", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public String channelAccessPackageInterface(@ApiParam @RequestBody RequestChannelAccess requestChannelAccess) {
        String requestStr = JSON.toJSONString(requestChannelAccess);
        System.out.println("前端请求报文是：" + requestStr);
        // 1，生成流水号
        String ConnSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = df.format(new Date());

        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();

        requestChannelAccess = JSONArray.parseObject(requestStr, RequestChannelAccess.class);
        String requestSign = requestChannelAccess.getSign();
        if (requestChannelAccess.getSign() == null) {
            System.out.println("请求报文不合法:sign为空");
            String jsonString = utils.dataWeiKong(ConnSeqNo, createTime);
            return jsonString;
        } else {
            System.out.println("请求的签名是：" + requestSign);
            //获取到要用的参数
            RequestChannelAccessData requestData = requestChannelAccess.getData();
            if (requestChannelAccess.getData() == null) {
                System.out.println("请求报文不合法:data为空");
                String jsonString = utils.dataWeiKong(ConnSeqNo, createTime);
                return jsonString;
            } else {
                String connSeqNo = requestData.getConnSeqNo();
                String token = requestData.getToken();
                String partnerCode = requestData.getPartnerCode();
                String tradeTime = requestData.getTradeTime();
                if (requestData.getTradeData() == null) {
                    System.out.println("请求报文不合法:TradeData为空");
                    String jsonString = utils.dataWeiKong(ConnSeqNo, createTime);
                    return jsonString;

                } else {
                    String deviceId = requestData.getTradeData().getDeviceId();
                    String deviceType = requestData.getTradeData().getDeviceType();
                    String notyfy_URL = requestData.getTradeData().getNotyfy_URL();
                    System.out.println("设备号：" + deviceId + ";设备类型：" + deviceType + ";回调地址：" + notyfy_URL);

                    if (deviceId == null || deviceId.length() <= 0 || deviceType == null || deviceType.length() <= 0 || notyfy_URL == null || notyfy_URL.length() <= 0 || connSeqNo == null || connSeqNo.length() <= 0 || token == null || token.length() <= 0 || partnerCode == null || partnerCode.length() <= 0 || tradeTime == null || tradeTime.length() <= 0) {
                        //参数不全,回复报文
                        System.out.println("请求报文不合法:参数不全！");
                        String jsonString = utils.dataWeiKong(ConnSeqNo, createTime);
                        return jsonString;
                    } else {
                        // 验证签名：
                        // 将请求体json转成String
                        String str = JSON.toJSONString(requestData);
                        // 将Str拿去计算签名
                        String sign = utils.calculateSignature(str);
                        System.out.println("计算的签名是：" + sign);

                        if (!requestSign.equalsIgnoreCase(sign)) {
                            // 如果收到的签名跟算出的签名相同才可以回复正确的报文
                            System.out.println("请求报文签名验证失败");
                            String jsonString = utils.signatureFailMessage(connSeqNo, tradeTime, partnerCode, token, deviceId, deviceType);
                            return jsonString;

                        } else {
                            //签名通过
                            //此时要判断一下访问的数据是不是合法的
                            int count = devicePartnerAccessService.findExitOrNotByAccess(token, partnerCode, deviceType);
                            if (count <= 0) {
                                //说明 token或者partnerCode有误
                                System.out.println("请求报文token/partnerCode/deviceType验证失败");
                                String jsonString = utils.FailMessageTokenOrPartnerCode(connSeqNo, tradeTime, partnerCode, token, deviceId, deviceType);
                                return jsonString;
                            } else {
                                //判断一下参数的合法性
                                if (("1".equals(deviceType) || "2".equals(deviceType) || "5".equals(deviceType)) && null != deviceId && true != deviceId.isEmpty() && 15 == deviceId.length()) {
                                    //SOC的设备 deviceId是15位的imei号
                                    //将合作伙伴访问的记录保存下来
                                    DevicePartnerAccess access = new DevicePartnerAccess();
                                    access.setConnSeqNo(connSeqNo);
                                    access.setToken(token);
                                    access.setPartnerCode(partnerCode);
                                    access.setDeviceId(deviceId);
                                    access.setDeviceType(deviceType);
                                    access.setNotyfy_URL(notyfy_URL);
                                    access.setTradeTime(tradeTime);
                                    access.setSign(requestSign);
                                    devicePartnerAccessService.putInPartnerAccessInfo(access);

                                    ResponseChannelAccessTradeData tradeData = new ResponseChannelAccessTradeData();
                                    tradeData.setH5url("http://wx.linksfield.net/#/");
                                    tradeData.setPartnerCode(partnerCode);
                                    tradeData.setDeviceId(deviceId);
                                    tradeData.setDeviceType(deviceType);

                                    ResponseChannelAccessData data = new ResponseChannelAccessData();
                                    data.setConnSeqNo(connSeqNo);
                                    data.setToken(token);
                                    data.setTradeTime(createTime);
                                    data.setTradeRstCode(1000);
                                    data.setTradeRstMessage("success");
                                    data.setTradeData(tradeData);

                                    ResponseChannelAccess responseChannelAccess = new ResponseChannelAccess();
                                    responseChannelAccess.setData(data);
                                    responseChannelAccess.setSign(MD5.calcMD5(JSON.toJSONString(data)));

                                    String jsonString = JSON.toJSONString(responseChannelAccess);
                                    System.out.println("输出的结果是：" + jsonString);
                                    return jsonString;

                                } else if (("3".equals(deviceType) || "4".equals(deviceType)) && null != deviceId && true != deviceId.isEmpty() && 20 == deviceId.length()) {
                                    //卡（旅游卡或者物联网卡）的设备 deviceId是20位的iccid号
                                    //将合作伙伴访问的记录保存下来
                                    DevicePartnerAccess access = new DevicePartnerAccess();
                                    access.setConnSeqNo(connSeqNo);
                                    access.setToken(token);
                                    access.setPartnerCode(partnerCode);
                                    access.setDeviceId(deviceId);
                                    access.setDeviceType(deviceType);
                                    access.setNotyfy_URL(notyfy_URL);
                                    access.setTradeTime(tradeTime);
                                    access.setSign(requestSign);
                                    devicePartnerAccessService.putInPartnerAccessInfo(access);

                                    ResponseChannelAccessTradeData tradeData = new ResponseChannelAccessTradeData();
                                    tradeData.setH5url(Constant.BASE_H5URL);
                                    tradeData.setPartnerCode(partnerCode);
                                    tradeData.setDeviceId(deviceId);
                                    tradeData.setDeviceType(deviceType);

                                    ResponseChannelAccessData data = new ResponseChannelAccessData();
                                    data.setConnSeqNo(connSeqNo);
                                    data.setToken(token);
                                    data.setTradeTime(createTime);
                                    data.setTradeRstCode(1000);
                                    data.setTradeRstMessage("success");
                                    data.setTradeData(tradeData);

                                    ResponseChannelAccess responseChannelAccess = new ResponseChannelAccess();
                                    responseChannelAccess.setData(data);
                                    responseChannelAccess.setSign(MD5.calcMD5(JSON.toJSONString(data)));

                                    String jsonString = JSON.toJSONString(responseChannelAccess);
                                    System.out.println("输出的结果是：" + jsonString);
                                    return jsonString;

                                } else {
                                    //这里就是deviceId和deviceType终极不合法的情况
                                    String jsonString = utils.FailMessageDeviceIdOrDeviceType(connSeqNo, tradeTime, partnerCode, token, deviceId, deviceType);
                                    return jsonString;
                                }
                            }

                        }
                    }
                }
            }
        }
    }
}
